﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SocketSuperLib
{
    public class BufferByte
    {
        //字节缓存区
        private byte[] buf;  
        //索引标记
        private int mark = 0; 
        //缓存区字节数组的长度
        private int capacity = 1024;

        public BufferByte() {
            buf = new byte[this.capacity];
        }

        public BufferByte(int capacity)
        {
            this.capacity = capacity;
            buf = new byte[this.capacity];
        }
        /// <summary>
        /// 添加信息到缓存区
        /// </summary>
        /// <param name="b"></param>
        public void Push(byte[] b,int len)
        {
            if (len <= 0)
                return;
            if (len > b.Length)
                len = b.Length;
            if (mark + len >= capacity) 
                Allocate(len); 
            for (int i = 0; i < len; i++)
                buf[mark++] = b[i]; 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="len"></param>
        private void Allocate(int len)
        { 
            byte[] temp = new byte[capacity + len];
            for (int i = 0; i < this.capacity; i++)
                temp[i] = buf[i]; 
            this.capacity += len; 
            this.buf = temp;
        }

        /// <summary>
        /// 转化数组
        /// </summary>
        /// <returns></returns>
        public byte[] ToArray()
        {
            byte[] dest = new byte[mark + 1];
            Array.Copy(buf, 0, dest, 0, mark+1); 
            return dest;
        }

        public void Clear()
        {
            this.capacity = 1024;
            this.buf = new byte[this.capacity];
            this.mark = 0;
        }
    }
}
